// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:37
describe: 相关性分析相关功能
*/

use crate::svc::base::{DataFrame, StyleConfig};
use serde_json::Value;
use std::collections::HashMap;

/// 显示相关性矩阵
pub fn show_correlation(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("指标", crate::svc::base::DataType::String, false);
    result.add_column("相关性", crate::svc::base::DataType::Number, true);
    result.add_column("P值", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示截面IC
pub fn show_sectional_ic(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("日期", crate::svc::base::DataType::String, false);
    result.add_column("IC", crate::svc::base::DataType::Number, true);
    result.add_column("IC_IR", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示时间序列滚动相关性
pub fn show_ts_rolling_corr(df: &DataFrame, window: usize, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("日期", crate::svc::base::DataType::String, false);
    result.add_column("滚动相关性", crate::svc::base::DataType::Number, true);
    result.add_column("置信区间", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示时间序列自相关性
pub fn show_ts_self_corr(df: &DataFrame, max_lag: usize, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("滞后", crate::svc::base::DataType::Number, false);
    result.add_column("自相关性", crate::svc::base::DataType::Number, true);
    result.add_column("置信区间", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示协整性分析
pub fn show_cointegration(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("变量对", crate::svc::base::DataType::String, false);
    result.add_column("协整系数", crate::svc::base::DataType::Number, true);
    result.add_column("P值", crate::svc::base::DataType::Number, true);
    result.add_column("是否协整", crate::svc::base::DataType::Boolean, false);
    
    result
}

/// 显示相关性图
pub fn show_corr_graph(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("变量1", crate::svc::base::DataType::String, false);
    result.add_column("变量2", crate::svc::base::DataType::String, false);
    result.add_column("相关性", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示标的物相关性
pub fn show_symbols_corr(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("标的1", crate::svc::base::DataType::String, false);
    result.add_column("标的2", crate::svc::base::DataType::String, false);
    result.add_column("相关性", crate::svc::base::DataType::Number, true);
    result.add_column("距离", crate::svc::base::DataType::Number, true);
    
    result
}

/// 计算皮尔逊相关系数
pub fn calculate_pearson_correlation(x: &[f64], y: &[f64]) -> f64 {
    if x.len() != y.len() || x.is_empty() {
        return 0.0;
    }
    
    let n = x.len() as f64;
    let sum_x: f64 = x.iter().sum();
    let sum_y: f64 = y.iter().sum();
    let sum_xy: f64 = x.iter().zip(y.iter()).map(|(a, b)| a * b).sum();
    let sum_x2: f64 = x.iter().map(|a| a * a).sum();
    let sum_y2: f64 = y.iter().map(|b| b * b).sum();
    
    let numerator = n * sum_xy - sum_x * sum_y;
    let denominator = ((n * sum_x2 - sum_x * sum_x) * (n * sum_y2 - sum_y * sum_y)).sqrt();
    
    if denominator > 0.0 {
        numerator / denominator
    } else {
        0.0
    }
}

/// 计算斯皮尔曼相关系数
pub fn calculate_spearman_correlation(x: &[f64], y: &[f64]) -> f64 {
    if x.len() != y.len() || x.is_empty() {
        return 0.0;
    }
    
    // 计算排名
    let rank_x = calculate_ranks(x);
    let rank_y = calculate_ranks(y);
    
    calculate_pearson_correlation(&rank_x, &rank_y)
}

/// 计算排名
fn calculate_ranks(data: &[f64]) -> Vec<f64> {
    let mut indexed: Vec<(usize, f64)> = data.iter().enumerate().collect();
    indexed.sort_by(|a, b| a.1.partial_cmp(b.1).unwrap());
    
    let mut ranks = vec![0.0; data.len()];
    let mut current_rank = 1.0;
    let mut i = 0;
    
    while i < indexed.len() {
        let mut j = i;
        let current_value = indexed[i].1;
        
        // 处理相同值
        while j < indexed.len() && indexed[j].1 == current_value {
            j += 1;
        }
        
        // 计算平均排名
        let avg_rank = (current_rank + (j - 1) as f64) / 2.0;
        for k in i..j {
            ranks[indexed[k].0] = avg_rank;
        }
        
        current_rank = j as f64;
        i = j;
    }
    
    ranks
}

/// 计算滚动相关性
pub fn calculate_rolling_correlation(x: &[f64], y: &[f64], window: usize) -> Vec<f64> {
    if x.len() != y.len() || x.len() < window {
        return vec![];
    }
    
    let mut correlations = Vec::new();
    
    for i in (window - 1)..x.len() {
        let x_window = &x[(i - window + 1)..=i];
        let y_window = &y[(i - window + 1)..=i];
        correlations.push(calculate_pearson_correlation(x_window, y_window));
    }
    
    correlations
} 